<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\model\LifeServiceConfig;
use think\facade\Cache;

class LifeServiceConfigController
{
    /**
     * 获取配置列表
     */
    public function index()
    {
        $list = LifeServiceConfig::field('id,business_type,platform_profit_rate,status,create_time')
            ->append(['business_type_text', 'profit_rate_percent'])
            ->select();
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $list]);
    }

    /**
     * 更新利润率配置
     */
    public function update($id)
    {
        $config = LifeServiceConfig::find($id);
        if (!$config) {
            return json(['code' => 1, 'msg' => '配置不存在']);
        }

        $profitRate = input('platform_profit_rate/f');
        if ($profitRate < 0 || $profitRate > 1) {
            return json(['code' => 1, 'msg' => '利润率必须在0-1之间']);
        }

        $config->save([
            'platform_profit_rate' => $profitRate
        ]);

        // 清除利润率缓存
        LifeServiceConfig::clearCache();

        return json(['code' => 0, 'msg' => '更新成功']);
    }

    /**
     * 更新状态
     */
    public function updateStatus($id)
    {
        $config = LifeServiceConfig::find($id);
        if (!$config) {
            return json(['code' => 1, 'msg' => '配置不存在']);
        }

        $status = input('status/d');
        if (!in_array($status, [1, 2])) {
            return json(['code' => 1, 'msg' => '状态值无效']);
        }

        $config->save([
            'status' => $status
        ]);

        // 清除利润率缓存
        LifeServiceConfig::clearCache();

        return json(['code' => 0, 'msg' => '更新成功']);
    }
} 